package com.swxy.club.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.swxy.club.dto.bo.LoginUserBO;
import com.swxy.club.result.Result;
import com.swxy.club.service.UserService;
import com.swxy.club.utils.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 易
 */
@RestController
@RequestMapping
@RequiredArgsConstructor
@Api(tags = "登入登出服务")
public class LoginController {

    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;


    @PostMapping("/login")
    @ApiOperation("用户登入")
    public Result login(@Valid @RequestBody LoginUserBO loginUserBO, HttpSession session){
        return Result.success(userService.login(loginUserBO,session));
    }


    @GetMapping("/outLogin")
    @ApiOperation("用户登出")
    public Result loginOut(HttpSession session) {
        session.removeAttribute("user_session");
        UserContext.clear();
        return Result.success("退出成功");
    }

    @GetMapping("/captcha")
    @ApiOperation("图形验证码")
    public void verify(HttpSession session, HttpServletResponse response) throws IOException {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 4, 0);
        captcha.write(response.getOutputStream());
        String verifyCode = captcha.getCode();
        String key = "verifyCode:" + session.getId();
        redisTemplate.opsForValue()
                .set(key, verifyCode, 60, TimeUnit.SECONDS);
    }

}
